package com.my.demos.controller;

import com.my.demos.config.DelayedQueueConfig;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2023/12/1 11:06
 */
@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMessageController {
    
    @Resource
    private RabbitTemplate rabbitTemplate;
    
    @ApiOperation("发消息")
    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@ApiParam(name = "message", value = "消息") @PathVariable("message") String message){
        
        log.info("当前时间:{}, 发送一条消息给两个TTL队列:{}", new Date().toString(), message);
        
        rabbitTemplate.convertAndSend("X", "XA", "消息来自TTL为10s的队列:" + message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自TTL为40s的队列:" + message);
    }
    
    
    // 开始发消息 消息 TTL
    @ApiOperation("开始发消息 消息 TTL")
    @GetMapping("sendExpirationMsg/{message}/{ttlTime}")
    public void sendMsg(@PathVariable("message") String message, @PathVariable("ttlTime") String ttlTime){
        log.info("当前时间:{}, 发送一条时长{}毫秒TTL信息给队列QC:{}", 
                new Date().toString(), ttlTime, message);
        rabbitTemplate.convertAndSend("X", "XC", "消息来自TTL为" + ttlTime + "的队列:" + message, message1 -> {
            // 发送消息的延迟时长
            message1.getMessageProperties().setExpiration("20000");
            return message1;
        });
    }
    
    // 开始发消息 基于插件 消息 及 延迟时间
    @GetMapping("/sendDelayMsg/{message}/{delayTime}")
    public void sendMsg(@PathVariable("message") String message,
                        @PathVariable("delayTime") Integer delayTime){
        log.info("当前时间:{}, 发送一条时长{}毫秒消息给延迟队列delayed.queue:{}",
                new Date(), delayTime, message);
        
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME, DelayedQueueConfig.DELAYED_ROUTING_KEY, message,
                msg -> {
                    // 发送消息时 延迟时长 单位ms
                    msg.getMessageProperties().setDelay(delayTime);
                    return msg;
                });
    }
    
    // 开始发消息 测试确认
    
}
